package handler;

import bean.UserInfo;
import context.ComClientContext;
import enums.MessageTypeEnum;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import message.LoginMessage;
import message.Message;

import java.util.Scanner;

public class ComClientInboundChannelHandler extends SimpleChannelInboundHandler<Message> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ComClientContext.comContext().setClientChannel(ctx.channel());
        super.channelActive(ctx);
        startLogin();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        System.out.println(ctx.channel().id() + " : " + msg.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Message msg) throws Exception {
        if(MessageTypeEnum.LOGIN.getCode().equals(msg.getType())){
            ComClientContext.userInfo = ((LoginMessage) msg).getUserInfo();
        }
    }

    private void startLogin(){
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            UserInfo userInfo = ComClientContext.userInfo;
            while (userInfo == null || !ComClientContext.isLogin()){
                System.out.print("输入用户名：");
                String user = scanner.nextLine();
                System.out.print("输入密码：");
                String pass = scanner.nextLine();
                UserInfo message = new UserInfo(user, pass);

                LoginMessage loginMessage = new LoginMessage(message);
                if(!ComClientContext.isLogin()){
                    ComClientContext.comContext().clientSendMessageToServer(loginMessage);
                }else {
                    System.out.println("无需重复登陆");
                }
            }
            while (ComClientContext.isLogin()){

            }
        }).start();
    }
}
